package com.dushuren.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dushuren.project.common.BaseResponse;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.common.ResultUtils;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.TagMapper;
import com.dushuren.project.model.dto.DeleteRequest;
import com.dushuren.project.model.dto.TagQueryRequest;
import com.dushuren.project.model.entity.Tag;
import com.dushuren.project.model.entity.User;
import com.dushuren.project.model.enums.TagCategoryEnum;
import com.dushuren.project.service.TagService;
import com.dushuren.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/tag")
@Slf4j
public class TagController {

  @Resource
  TagService tagService;
  @Resource
  TagMapper tagMapper;

  // TagMap 缓存
  private final Cache<String, Map<String, List<Tag>>> tagMapCache = Caffeine.newBuilder().build();

  // 整个 TagMap 缓存 key
  private static final String FULL_TAG_MAP_KEY = "f";

  @Resource
  UserService userService;
  /**
   * 添加列表
   */
  @PostMapping("/add")
  public BaseResponse<Long> addTag(@RequestBody Tag tag, HttpServletRequest request) {
    if (tag == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    String tagName = tag.getTagName();
    String category = tag.getCategory();
    if (StringUtils.isAllBlank(tagName, category)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    tagService.count();
    userService.isAdministrators(request);
    User loginUser = userService.getLoginUser(request);
    tag.setUserId(loginUser.getId());
    boolean save = tagService.save(tag);
    if (Boolean.FALSE.equals(save)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    // 清除缓存
    tagMapCache.invalidate(FULL_TAG_MAP_KEY);
    return ResultUtils.success(tag.getId());
  }

  /**
   * 删除
   */
  @PostMapping("/delete")
  public BaseResponse<Boolean> deleteTag(@RequestBody DeleteRequest deleteRequest) {
    if (deleteRequest == null || deleteRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    long id = deleteRequest.getId();
    boolean b = tagService.removeById(id);
    // 清除缓存
    tagMapCache.invalidate(FULL_TAG_MAP_KEY);
    return ResultUtils.success(b);
  }

  /**
   * 获取所有标签分组
   *
   * @return
   */
  @GetMapping("/get/map")
  public BaseResponse<Map<String, List<Tag>>> getTagMap() {
    // todo 改为redis存储 hash
//    List<Tag> tagList = tagService.list();
    QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id", "category", "tagName", "postNum", "userId");
    List<Tag> tagList = tagMapper.selectList(queryWrapper);
    if (tagList == null) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    // todo 修改成redis
    // 优先取缓存
    Map<String, List<Tag>> tagMap = tagMapCache.get(FULL_TAG_MAP_KEY, key -> tagList.stream().map(tag -> {
      // 精简
      Tag newTag = new Tag();
      newTag.setTagName(tag.getTagName());
      newTag.setCategory(tag.getCategory());
      newTag.setPostNum(tag.getPostNum());
      return newTag;
      // 按类别分组
    }).collect(Collectors.groupingBy(Tag::getCategory)));
    return ResultUtils.success(tagMap);
  }

  /**
   * 分页查询标签（仅管理员可见）
   *
   * @return
   */
  @GetMapping("/list/page")
  public BaseResponse<Page<Tag>> listTagByPage(TagQueryRequest tagQueryRequest) {
    if (tagQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    long current = tagQueryRequest.getCurrent();
    long size = tagQueryRequest.getPageSize();
    String category = tagQueryRequest.getCategory();
    String tagName = tagQueryRequest.getTagName();
    QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
    if (StringUtils.isNotBlank(category)) {
      queryWrapper.eq("category", category);
    }
    if (StringUtils.isNotBlank(tagName)) {
      queryWrapper.like("tagName", tagName);
    }
    // 默认按帖子使用数降序排序
    queryWrapper.orderByDesc("postNum");
    Page<Tag> tagPage = tagService.page(new Page<>(current, size), queryWrapper);
    return ResultUtils.success(tagPage);
  }

/**
 * 分页查询标签（仅管理员可见）
 *
 * @return
 */
  @GetMapping("/category/list")
  public BaseResponse<List<String>> listTagCategory() {
    return ResultUtils.success(TagCategoryEnum.getValues());
  }

}
